import os
import random
import re
import time

import requests
from lxml import etree


class song(object):
    def set_user_agent(self):
        USER_AGENTS = [
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
            "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
            "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
            "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5"
        ]
        user_agent = random.choice(USER_AGENTS)
        return user_agent

    def spider(self, song_id):
        time.sleep(0.3)
        song_url = 'https://music.163.com/song'
        headers = {
            'Accept-Language': "zh-CN,zh;q=0.9,en;q=0.8",
            'dnt': '1',
            'referer': 'https://music.163.com/',
            'sec-fetch-dest': 'iframe',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'upgrade-insecure-requests': '1',
            'User-Agent': self.set_user_agent()
        }
        param = {'id':song_id,
                 'userid':357301093}

        response = requests.get(url=song_url, params=param, headers=headers).content.decode()
        return response

    def song_info(self, response):
        tree = etree.HTML(response)
        song_title0 = tree.xpath('//script[@type="application/ld+json"]/text()')[0]
        """
            <script type="application/ld+json">
            {
            "@context": "https://ziyuan.baidu.com/contexts/cambrian.jsonld",
            "@id": "http://music.163.com/song?id=1482614803",
            "appid": "1582028769404989",
            "title": "不再 (feat. 陈宥如)",
            "images": ["http://p1.music.126.net/pIXlzFCzIPMG0RcnXJ9GXw==/109951165347506779.jpg"],
            "description": "歌曲名《不再 (feat. 陈宥如)》，由 IZZI、MiraclE、陈宥如 演唱，收录于《RE: CONNECT》专辑中。《不再 (feat. 陈宥如)》下载，《不再 (feat. 陈宥如)》在线试听，更多相关歌曲推荐尽在网易云音乐",
            "pubDate": "2020-09-28T00:00:00"
            }
            </script>
        """ #script[@type="application/ld+json"]
        #print(song_title0)

        global img_url
        img_url = re.findall(r'"images": \["(.*?)"', str(song_title0))[0]
        img_url = 'https' + img_url[4:]
        # print(img_url)

        song_title1 = re.findall(r'description": "(.+)"', str(song_title0))[0]

        #歌曲名《不再(feat.陈宥如)》，由 IZZI、MiraclE、陈宥如 演唱，收录于《RE: CONNECT》专辑中
        song_name = re.findall(r'"title": "(.+)",', song_title0)[0]
        singer0 = re.findall(r'，由 (.+) 演唱，', song_title1)[0]
        if '、' in singer0:
            singer = singer0.replace('、', ',')
        else:
            singer = singer0
        album_name = re.findall(r'收录于《(.+)》专辑中', song_title1)[0]

        global song_info
        song_info = f'{singer} - {song_name}'
        print(f'Singers : {singer}\nSongName : {song_name}\nSongInfo : {song_info}\nAlbumName : {album_name}')
        # print(song_info)
        return song_info


    def album_img(self, song_name):
        print(img_url)

        headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1; MZ-m1 metal Build/LMY47I) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0'}
        img_data = requests.get(url=img_url, headers=headers).content

        # if not os.path.exists(f'./{song_info}'):
        #     os.mkdir(f'./{song_info}')
        # with open(f'./{song_info}/{song_name}.jpg', 'wb') as fp:
        #     fp.write(img_data)
            
        if not os.path.exists('img'):
            os.mkdir('img')
            
        with open(f'./img/{song_name}.jpg', 'wb') as fp:
            fp.write(img_data)    

        print(f'{song_name}.jpg 保存完成!')


    def run(self, song_id):
        print('获得歌曲信息——————————————————')
        response = self.spider(song_id)
        song_info_str = self.song_info(response)
        print('获取专辑封面——————————————————')
        self.album_img(song_info_str)
        print('获得歌曲信息部分结束——————————————————')
        return song_info_str

    def run_not_img(self, song_id):
        response = self.spider(song_id)
        song_info_str = self.song_info(response)
        return song_info_str


if __name__ == '__main__':
    song_id = input('网易云歌曲id：') #  1398628590  1482614803    400161906
    song_info = song()
    print()
    song_info.run(song_id)


'''
https://music.163.com/song?id=29797443&userid=357301093
'''